<template>
  <div class="component-manage-level-ordinary distribution-level-set1 bottom-redius">
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('user:userLevel:save')"
          class="default-btn primary-btn"
          :class="{'disabled-btn': maxNeedGrowth === 1000000000}"
          @click.stop="onAAddRow()"
        >
          {{ $t("user.addLevel") }}
          <el-tooltip effect="light">
            <template #content>
              <div

                style="max-width:500px"
              >
                {{ $t("user.addLevelTip") }}
              </div>
            </template>
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
        <div
          v-if="isUpdateData"
          class="default-btn"
          @click="onUpdateUserLevel"
        >
          {{ $t('user.updateUserData') }}
        </div>
        <el-tag
          v-if="isUpdateData"
          class="operation-tag"
          type="warning"
        >
          {{ $t('user.updateSoon') }}
        </el-tag>
      </div>
      <!-- <el-checkbox v-model="dataForm.levelSetConditionsSwitch.boundCustomers">绑定客户数</el-checkbox>
      <el-checkbox v-model="dataForm.levelSetConditionsSwitch.invitedVeeker">邀请分销员数</el-checkbox>-->
      <div class="table-con">
        <el-table
          :data="dataForm.userLevels"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          class="level-table"
        >
          <el-table-column
            prop="level"
            fixed
            :label="$t('distribution.grade')"
            width="100"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.level }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="levelName"
            fixed
            :label="$t('user.levelName')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.levelName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="img"
            fixed
            :label="$t('user.bgImg')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img
                  v-if="scope.row.img"
                  :src="checkFileUrl(scope.row.img)"
                  width="140"
                  height="60"
                  @error="scope.row.img=''"
                >
                <span
                  v-if="!scope.row.img"
                  style="line-height: 60px"
                >{{ $t('prodList.noPictures') }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="presScore"
            fixed
            :label="$t('user.bonusPoints')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.presScore }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="needGrowth"
            :label="$t('user.growthRange')"
          >
            <template #default="scope">
              <div>
                <span>{{ scope.row.needGrowth }}</span>
                <span v-if="scope.$index < dataForm.userLevels.length-1">~</span>
                <span
                  v-if="scope.$index < dataForm.userLevels.length-1"
                >{{ dataForm.userLevels[scope.$index+1].needGrowth-1 }}</span>
                <span v-if="scope.$index === dataForm.userLevels.length-1">~ ∞</span>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="prodId" label="赠送优惠券" align="center" min-width="80px" fit>
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.couponList" :key="index">
                <span
                  v-if="index < 1"
                >{{item.couponName}} {{scope.row.couponList.length>1?'等优惠券':''}}</span>
              </div>
            </template>
          </el-table-column>-->
          <el-table-column
            prop="discountRange"
            :label="$t('user.memberDiscount')"
          >
            <template #default="scope">
              <span v-if="scope.row.discount==10">{{ $t('chat.none') }}</span>
              <span v-else>
                <!-- {{scope.row.term}}
                {{scope.row.termType === 1?'天':scope.row.termType === 2?'周':scope.row.termType === 3?'月':scope.row.termType === 4?'季度':'年'}}内-->
                {{ scope.row.discountRange === 1? $t('user.selfShop') : $t('user.platform') }}
                {{ scope.row.discountType === 1? $t('user.someProducts') : $t('user.allProducts') }}
                {{ scope.row.discount }}{{ $t('coupon.off') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="150"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="text-btn default-btn"
                  @click="onAddOrUpdate(scope.$index)"
                >
                  {{ scope.$index+1 > maxLength ? $t('sysManagement.save') : $t('coupon.edit') }}
                </div>
                <div
                  v-if="scope.$index === dataForm.userLevels.length -1 && scope.$index !== 0"
                  class="text-btn default-btn"
                  @click="onDeleteRow(scope.$index)"
                >
                  {{ $t('user.remove') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetData"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'

const addOrUpdateVisible = ref(false)
const dataForm = reactive({
  parentId: null,
  id: null,
  levelType: 0,
  userLevels: []
})
const maxLength = ref(0)
const maxNeedGrowth = ref(0)
const isUpdateData = ref(false)
const userLevel = [
  {
    id: null,
    level: 0,
    levelName: '',
    levelNameCn: '',
    levelNameEn: '',
    levelType: 0,
    needGrowth: 0,
    term: 1,
    termType: 3,
    img: '',
    discount: 10,
    discountRange: 0,
    discountType: 0,
    presScore: 0,
    rateScore: 1,
    isFreeFee: 0,
    couponList: [],
    userRightsIds: [],
    categorys: null
  }
]
onMounted(() => {
  onGetData()
})

// 获取数据
const onGetData = () => {
  http({
    url: http.adornUrl('/user/userLevel/list'),
    method: 'get',
    params: http.adornParams({
      userLevelType: 0
    })
  }).then(({ data }) => {
    getVipInternationalization(data)
    dataForm.userLevels = data
    maxLength.value = data.length
    dataForm.userLevels.forEach(item => {
      if (item.status === -1) {
        isUpdateData.value = true
      }
      maxNeedGrowth.value = item.needGrowth
    })
  })
}
// const handleChange = (val) => {
//   dataForm.parentId = val[val.length - 1]
// }
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (index) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(dataForm.userLevels, index)
  })
}
// 删除列
const onDeleteRow = (index) => {
  // var bool = true
  // for (var i = 0; i < dataForm.userLevels.length; i++) {
  //   if (i === index && bool) {
  //     dataForm.userLevels.splice(index, 1)
  //     bool = false
  //     i--
  //   } else if (i < index) {
  //   } else {
  //     dataForm.userLevels[i].level = i + 1
  //   }
  // }

  ElMessageBox.confirm($t('seckill.isDeleOper'), $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    type: 'warning'
  }).then(() => {
    // if (dataForm.userLevels.length === 2) {
    //   errorMsg('最后一个会员等级不能删除')
    // }
    dataForm.id = dataForm.userLevels[index].id
    // 删除列并更新数据
    if (dataForm.id) {
      http({
        url: http.adornUrl('/user/userLevel'),
        method: 'delete',
        data: http.adornData(dataForm)
      }).then(() => {
        isUpdateData.value = false
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
        onGetData()
      }).catch(() => { })
    } else {
      onGetData()
    }
  }).catch(() => { })
}
// 增加列
const onAAddRow = () => {
  if (maxNeedGrowth.value >= 1000000000) {
    return
  }
  if (dataForm.userLevels.length >= 50) {
    ElMessage({
      message: $t('user.atMost'),
      type: 'warning'
    })
    return
  }
  if (dataForm.userLevels.length > maxLength.value) {
    ElMessage({
      message: $t('user.saveFirst'),
      type: 'warning'
    })
    return
  }
  let needGrowth = 0
  if (dataForm.userLevels.length > 0) {
    needGrowth = dataForm.id = dataForm.userLevels[maxLength.value - 1].needGrowth === 1000000000 ? 1000000000 : dataForm.userLevels[maxLength.value - 1].needGrowth + 1
  }
  const level = JSON.parse(JSON.stringify(userLevel[0]))
  level.levelId = null
  level.level = dataForm.userLevels.length + 1
  // if (level.conditionData.commodity) {
  //   level.conditionData.commodity = []
  // }
  const levelNum = parseInt(dataForm.userLevels.length) + 1
  level.levelName = $t('user.membershipLevel') + levelNum
  level.levelNameCn = $t('user.membershipLevel') + levelNum
  dataForm.userLevels.push(level)
  dataForm.userLevels[maxLength.value].needGrowth = needGrowth
  onAddOrUpdate(dataForm.userLevels.length - 1)
}
const onUpdateUserLevel = () => {
  http({
    url: http.adornUrl('/user/userLevel/updateUserLevel'),
    method: 'put',
    data: http.adornData({
      levelType: 0
    })
  }).then(() => {
    location.reload()
  })
}
// const errorMsg = (message) => {
//   ElMessage({
//     message,
//     type: 'error',
//     duration: 1500
//   })
// }
// 国际化
const getVipInternationalization = (data) => {
  if (!data) return
  const lang = localStorage.getItem('bbcLang') || 'zh_CN'
  data.map(element => {
    let levelNameCn, levelNameEn
    if (!element.userLevelLangList) return element
    element.userLevelLangList.map(val => {
      if (val.lang === 0) {
        levelNameCn = val.levelName
      }
      if (val.lang === 1) {
        levelNameEn = val.levelName
      }
      return val
    })
    element.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
    element.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
    return element
  })
}

</script>

<style lang="scss" scoped>
.component-manage-level-ordinary.distribution-level-set1 {
  .operation-bar {
    margin-top: 5px;
    &:empty{
      display: none;
    }
    .operation-tag {
      margin-left: 20px;
    }
  }
}
</style>
